import pandas as pd
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.impute import KNNImputer

df = pd.read_csv("D:\数据挖掘\数据预处理-两次实验\数据预处理-实验2\\titanic.csv", usecols=['PassengerId','Survived','Pclass','Name','Sex','Age','SibSp','Parch','Ticket','Fare','Cabin','Embarked'])
result=df.isna().sum()
print("\n",result)

#删除Cabin属性
df.drop(['Cabin'],axis=1,inplace=True)
print("\n",df)

#使用众数填充Embarked缺失值
mode=df['Embarked'].value_counts().index[0]
print("众数是",mode)
df['Embarked'].fillna(value=mode,inplace=True)
print("使用众数填充Embarked缺失值\n",df)

#mean knn填充age缺失值
#mean imputation
df=np.array(df['Age']).reshape(1, -1)  #转为一维数组
imp_mean = SimpleImputer(missing_values=np.nan, strategy='mean')
X1=imp_mean.fit_transform(df)
print("mean imputation\n",X1)

#KNN imputation
imp_KNN = KNNImputer(n_neighbors=2)
X2=imp_KNN.fit_transform(df)
print("KNN imputation\n",X2)